package cn.keniykey.mc.landterritory.landflag.api;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import org.bukkit.Bukkit;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;

import cn.keniykey.mc.landterritory.LandTerritoryMain;
import cn.keniykey.mc.landterritory.landflag.LandFlag;

public final class LandFlagListenerManager {
	private LandFlagListenerManager() {}
	
	private static HashMap<String,HashSet<Listener>> hashmap_liss = new HashMap<>();
	private static HashMap<Listener,String> hashmap_lisfalg = new HashMap<>();
	
	public static void registerListener(LandFlag flag,Listener listener) {
		if(hashmap_lisfalg.containsKey(listener)) return;
		final String name = flag.getName();
		final HashSet<Listener> hashset_lis;
		if(hashmap_liss.containsKey(name)) {
			hashset_lis = hashmap_liss.get(name);
		}else {
			hashset_lis = new HashSet<>();
			hashmap_liss.put(name, hashset_lis);
		}
		if(hashset_lis.contains(listener)) return;
		Bukkit.getPluginManager().registerEvents(listener, LandTerritoryMain.getPlugin());
		hashset_lis.add(listener);
		hashmap_lisfalg.put(listener, name);
	}
	public static void unRegisterListener(LandFlag flag) {
		final String name = flag.getName();
		if(!hashmap_liss.containsKey(name)) return;
		final HashSet<Listener> hashset_lis = hashmap_liss.get(name);
		if(hashset_lis.isEmpty()) return;
		final Iterator<Listener> it = hashset_lis.iterator();
		while(it.hasNext()) {
			final Listener lis = it.next();
			hashmap_lisfalg.remove(lis);
			HandlerList.unregisterAll(lis);
		}
		hashset_lis.clear();
	}
	public static void unRegisterListener(Listener lis) {
		if(!hashmap_lisfalg.containsKey(lis)) return;
		HandlerList.unregisterAll(lis);
		final String name = hashmap_lisfalg.remove(lis);
		if(!hashmap_liss.containsKey(name)) return;
		hashmap_liss.get(name).remove(lis);
	}
	public static void unRegisterListener() {
		if(hashmap_lisfalg.isEmpty()) return;
		for(final HashSet<Listener> hashset_lis : hashmap_liss.values()) {
			if(hashset_lis.isEmpty()) continue;
			for(final Listener lis : hashset_lis) HandlerList.unregisterAll(lis);
			hashset_lis.clear();
		}
		hashmap_liss.clear();
		hashmap_lisfalg.clear();
	}
}